package com.zhhs.wecom.core;


import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.zhhs.common.core.redis.Redis;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.common.redis.WxRedisOps;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @description: 微信配置信息
 * @author: xiaohu
 * @date: Created in 2021-11-02 12:03
 */
@Configuration
@Slf4j
public class WxConfig {
    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public WxPayService wxPayService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(wxPayProperties.getAppId());
        payConfig.setMchId(wxPayProperties.getMchId());
        payConfig.setMchKey(wxPayProperties.getMchKey());
        payConfig.setSubAppId(wxPayProperties.getSubAppId());
        payConfig.setSubMchId(wxPayProperties.getSubMchId());
        payConfig.setKeyPath(wxPayProperties.getKeyPath());
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        log.info("微信支付初始化完成...");
        return wxPayService;
    }


    @Bean
    public WxMpService wxMpService() {
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        WxRedisOps redisOps = new RedisTemplateWxRedisOps(new StringRedisTemplate(factory));
        WxMpRedisConfigImpl configStorage = new WxMpRedisConfigImpl(redisOps, Redis.getProjectName());
        configStorage.setAppId(wxMpProperties.getAppId());
        configStorage.setSecret(wxMpProperties.getSecret());
        configStorage.setToken(wxMpProperties.getToken());
        configStorage.setAesKey(wxMpProperties.getAesKey());
        WxMpService service = new WxMpServiceImpl();
        service.setWxMpConfigStorage(configStorage);
        log.info("微信公众号初始化完成...");
        return service;
    }
}
